import Layout from "@/layout/Index.vue";
import { RouteRecordRaw } from "vue-router";
import router from "@/router/index.ts";

interface MenuData {
  menuId: number;
  menuName: string;
  parentId: number;
  menuType: string;
  path: string;
  component: string;
  icon: string;
  hidden: string;
  cache: string;
  redirect?: string;
}
/**
 * 注意：使用console.log("路由数据", JSON.stringify(generateRoutes(res.data, 0))打印会发现子路由的componet打印不出来，JSON不能打印出来函数。${data[i].component}
 */
// 递归函数用于生成路由配置，登录的时候也需要调用一次。
export function generateRoutes(
  data: MenuData[],
  parentId: number | null = null,
): RouteRecordRaw[] {
  // 首先把你需要动态路由的组件地址全部获取[vue2中可以直接用拼接的方式，但是vue3中必须用这种方式]
  let modules = import.meta.glob("@/views/**/*.vue");
  const routes: any = [];
  for (var i = 0; i < data.length; i++) {
    if (data[i] && !router.hasRoute(data[i].path)) {
      if (data[i].parentId === parentId) {
        // console.log("component",data[i].component)
        const componentTemplate = data[i].component;
        const route: any = {
          path: `/${data[i].path}`,
          name: `/${data[i].path}`,
          // 这里modules[`/src/views/${componentTemplate}.vue`] 一定要会用绝对定位
          component: data[i]?.component
            ? modules[`/src/views/${componentTemplate}.vue`]
            : Layout,
          meta: {
            title: data[i].menuName,
            icon: data[i].icon,
            hidden: data[i].hidden,
            cache: data[i].cache,
          },
        };
        // console.log("component",route.component)
        if (data[i].menuType == "1") {
          route.redirect = `/${data[i]?.redirect}` || "/home";
        }
        // 递归处理子节点
        const children = generateRoutes(data, data[i].menuId);
        if (children.length > 0) {
          route.children = children;
        }

        routes.push(route);
      }
    }
  }
  return routes;
}
